<template>
    <div class="report-tab">
        <Tabs :animated="false" @on-tab-remove="delTab" closable type="card" v-model="currentTab">
            <TabPane :closable="item.closable" :key="item.name" :label="item.label" :name="item.name" v-for="item in tabInfo.tabList">
                <reportList @goDetail="goDetail" v-if="item.name === 'list'"></reportList>
                <!-- <deviceDetail :id="Number(item.id)" :sn="item.name" v-else></deviceDetail> -->
            </TabPane>
        </Tabs>
    </div>
</template>

<script>
import reportList from './report-list.vue'
// import deviceDetail from './device-detail.vue';
// 同一个tab禁止多次打开
export default {
  components: {
    reportList
    // deviceDetail
  },
  data () {
    return {
      tabInfo: {
        actTab: 'list',
        tabList: [
          {
            closable: false,
            label: '设备明细',
            name: 'list'
          }
        ]
      }
    }
  },
  computed: {
    currentTab: {
      get () {
        return this.tabInfo.actTab
      },
      // 选项卡切换触发set函数，更新reportTab的sessionStorage
      set (name) {
        if (!name) {
          return
        }
        const sessionTab = JSON.parse(sessionStorage.getItem('reportTab'))
        sessionTab.actTab = name
        this.tabInfo.actTab = name
        sessionStorage.setItem('reportTab', JSON.stringify(sessionTab))
      }
    }
  },

  beforeDestroy () {
    sessionStorage.setItem('reportTab', null)
  },

  mounted () {
    const sessionTab = JSON.parse(sessionStorage.getItem('reportTab'))
    if (sessionTab) {
      this.tabInfo = sessionTab
    }
  },

  methods: {
    goDetail (label, id) {
      // 防止重复打开同一个详情
      let flag = true
      this.tabInfo.tabList.forEach(item => {
        if (item.name === label) {
          flag = false
        }
      })
      if (!flag) {
        return (this.currentTab = label)
      }

      const detailTab = {
        closable: true,
        id: id,
        label: label + ' - 详情',
        name: label
      }
      this.tabInfo.tabList.push(detailTab)

      // 记录已打开tab，用于防止浏览器刷新后已打开tab被关闭
      const sessionTab = {
        actTab: detailTab.name,
        tabList: this.tabInfo.tabList
      }
      sessionStorage.setItem('reportTab', JSON.stringify(sessionTab))
      this.tabInfo.actTab = detailTab.name
    },
    delTab (name) {
      this.tabInfo.tabList = this.tabInfo.tabList.filter(item => {
        return item.name !== name
      })

      let sessionTab = JSON.parse(sessionStorage.getItem('reportTab'))
      sessionTab.tabList = this.tabInfo.tabList
      sessionStorage.setItem('reportTab', JSON.stringify(sessionTab))
    }
  }
}
</script>

<style lang="less">
.report-tab {
    overflow-x: hidden;
    padding-bottom: 100px;
}
</style>
